var mainCustomerId = sessionStorage.getItem('mainCustomerId') //主客户id
// 操作人ID
var operateUserId = JSON.parse(decodeURIComponent(web.readCookie('loginData')))
    .user.user_ID
//操作人姓名
var operateUserName = JSON.parse(
    decodeURIComponent(web.readCookie('loginData'))
).user.name

// 列表数据源
var dataSource = []
// 获取接口数据
var getData = {
    // 获取查询列表
    searchMaterielData: function () {
        var skuCode = $('#skuCode').val() //商品编码
        var materielNumber = $('#materielNumber').val() //物料号
        var productType = $('#productType').val() //10 正常商品  20 临采商品
        var params = {
            mainCustomerId: mainCustomerId, //主客户id
            skuCode: skuCode, //商品编码
            materielNumber: materielNumber, //物料号
            productType: productType, //10 正常商品  20 临采商品
            pageNum: 1,
            pageSize: 10,
        }
        // 获取输入框的输入信息
        $.ajax({
            url: root.member.searchMaterielData,
            cache: false, //禁用缓存
            type: 'POST',
            dataType: 'json',
            contentType: 'application/json',
            data: JSON.stringify(params),
            success: function (data) {
                if (data.errorCode == 0 && data.data.data.length > 0) {
                    renderData.tableLists(data.data)
                    $('.M-box3').pagination({
                        pageCount: data.data.pageCount,
                        jump: true,
                        coping: true,
                        prevContent: '上页',
                        nextContent: '下页',
                        callback: function (api) {
                            var params = {
                                mainCustomerId: mainCustomerId, //主客户id
                                skuCode: skuCode, //商品编码
                                materielNumber: materielNumber, //物料号
                                productType: productType, //10 正常商品  20 临采商品
                                pageNum: api.getCurrent(),
                                pageSize: 10,
                            }
                            $.ajax({
                                url: root.member.searchMaterielData,
                                cache: false, //禁用缓存
                                type: 'POST',
                                dataType: 'json',
                                contentType: 'application/json',
                                data: JSON.stringify(params),
                                success: function (data) {
                                    renderData.tableLists(data.data)
                                },
                                error: function (msg) {
                                    $.Huimodalalert('失败！', 2000)
                                },
                            })
                        },
                    })
                } else {
                    $('.M-box3').pagination({
                        pageCount: 0,
                    })
                    renderData.tableLists(data.data)
                }
            },
            error: function (msg) {
                $.Huimodalalert(msg, 2000)
            },
        })
    },
    // 删除物料号
    deleteMaterielById: function (materielId) {
        var params = {}
        if (Array.isArray(materielId)) {
            params.materielIds = materielId
        } else {
            var materielAry = []
            materielAry.push(materielId)
            params.materielIds = materielAry
        }
        $.ajax({
            url: root.member.deleteMaterielById,
            cache: false, //禁用缓存
            type: 'POST',
            dataType: 'json',
            contentType: 'application/json',
            data: JSON.stringify(params),
            success: function (data) {
                if (data.errorCode == 0) {
                    $.Huimodalalert('删除成功', 2000)
                    $('#selectAll').prop('checked', false)
                    getData.searchMaterielData()
                }
            },
            error: function (msg) {
                $.Huimodalalert(msg, 2000)
            },
        })
    },
    //导出客户物料
    export_materiel: function () {
        window.location.href =
            root.member.export_materiel_Execl +
            '?mainCustomerId=' +
            mainCustomerId
    },
}
// 数据渲染
var renderData = {
    tableLists: function (data) {
        dataSource = []
        if (data != null && data != '') {
            var startRow = data.startRow + 1
            $.each(data.data, function (index, item) {
                var dataT = startRow++
                var obj = {}
                obj.materielNumber = item.materielNumber //客户物料号 skuName
                obj.materielUnitName = item.materielUnitName //客户单位
                obj.skuCode = item.skuCode //鑫方盛SKU编码
                obj.productType = item.productType // 10:正常商品 20:临采商品
                obj.skuName = item.skuName //商品名称
                obj.unitName = item.unitName //商品单位
                obj.updateTime = item.updateTime
                obj.materielId = item.materielId
                obj.dataT = dataT
                dataSource.push(obj)
            })
        }
        renderData.materialLists(dataSource)
    },
    // 渲染查询数据
    materialLists: function (data) {
        var datatable = $('#materiallists').dataTable() // 初始化dataTable，清空上一个值
        datatable.fnClearTable() //清空一下table
        datatable.fnDestroy() //还原初始化了的datatable
        $('#materiallists').DataTable({
            order: [[1, 'desc']],
            autoWidth: false,
            ordering: false,
            searching: false,
            paging: false,
            retrieve: true,
            destroy: true,
            bAutoWidth: true,
            bLengthChange: true,
            aLengthMenu: [5, 10, 25, 50],
            oLanguage: {
                sLengthMenu: '每页显示 _MENU_ 条记录',
                sZeroRecords: '抱歉， 没有找到',
                sInfo: '从 _START_ 到 _END_ /共 _TOTAL_ 条数据',
                sInfoEmpty: '',
                sInfoFiltered: '(从 _MAX_ 条数据中检索)',
                oPaginate: {
                    sFirst: '首页',
                    sPrevious: '前一页',
                    sNext: '后一页',
                    sLast: '尾页',
                },
                sZeroRecords: '没有检索到数据',
                /* "sProcessing": "<img src='./loading.gif' />",*/
            },
            data: data,
            columnDefs: [
                {
                    visible: true,
                    targets: 0,
                },
                {
                    render: function (data, type, row, meta) {
                        /*console.log(row.materielId)*/
                        return (
                            '<span style="text-align: center;"><td><input class="check" type="checkbox" name="checkbox" data-type=' +
                            row.materielId +
                            '></td></span>'
                        )
                    },
                    targets: 0,
                },
                {
                    render: function (data, type, row, meta) {
                        var materielNumber = row.materielNumber
                        if (materielNumber == undefined) {
                            materielNumber = ''
                        }
                        return (
                            '<span style="text-align: center;" >' +
                            materielNumber +
                            '</span>'
                        )
                    },
                    targets: 1,
                },
                {
                    render: function (data, type, row, meta) {
                        var materielUnitName = row.materielUnitName
                        if (materielUnitName == undefined) {
                            materielUnitName = ''
                        }
                        return (
                            '<span style="text-align: center;" >' +
                            materielUnitName +
                            '</span>'
                        )
                    },
                    targets: 2,
                },
                {
                    render: function (data, type, row, meta) {
                        var skuCode = row.skuCode
                        if (skuCode == undefined) {
                            skuCode = ''
                        }
                        return (
                            '<span style="text-align: center;">' +
                            skuCode +
                            '</span>'
                        )
                    },
                    targets: 3,
                },
                {
                    render: function (data, type, row, meta) {
                        var productType = row.productType
                        switch (productType) {
                            case 10:
                                return '正常商品'
                            case 20:
                                return '临采商品'
                            default:
                                ''
                        }
                        return (
                            '<span style="text-align: center;">' +
                            productType +
                            '</span>'
                        )
                    },
                    targets: 4,
                },
                {
                    render: function (data, type, row, meta) {
                        var skuName = row.skuName
                        if (skuName == undefined) {
                            skuName = ''
                        }
                        return (
                            '<span style="text-align: center;">' +
                            skuName +
                            '</span>'
                        )
                    },
                    targets: 5,
                },
                {
                    render: function (data, type, row, meta) {
                        var unitName = row.unitName
                        if (unitName == undefined) {
                            unitName = ''
                        }
                        return (
                            '<span style="text-align: center;">' +
                            unitName +
                            '</span>'
                        )
                    },
                    targets: 6,
                },
                {
                    render: function (data, type, row, meta) {
                        var updateTime = row.updateTime
                        if (updateTime == undefined) {
                            updateTime = ''
                        }
                        return (
                            '<span style="text-align: center;">' +
                            updateTime +
                            '</span>'
                        )
                    },
                    targets: 7,
                },
                {
                    render: function (data, type, row, meta) {
                        return (
                            '<span style="text-align: center; color: blue; margin-right: 10px; cursor: pointer" onclick="modify(\'' +
                            row.productType +
                            '\',this)"    data-type=' +
                            row.materielId +
                            ' >' +
                            '修改' +
                            '</span>' +
                            '<span style="text-align: center; color: #0000ff;cursor: pointer" onclick="cancelData(\'' +
                            row.materielId +
                            '\')" >' +
                            '删除' +
                            '</span>'
                        )
                    },
                    targets: 8,
                },
            ],
            fnInitComplete: function () {
                $('#materiallists').on('change', '.check', function () {
                    var num = $('.bodyTable').find(
                        'input[type=checkbox]:checked'
                    ).length
                    var selectTotalLength = $('.check').length
                    if (num == selectTotalLength) {
                        $('#selectAll').prop('checked', true)
                    } else {
                        $('#selectAll').prop('checked', false)
                    }
                })
            },
        })
    },
}
// 新增或是修改返回的时候要刷新物料号页面
if (getQueryString('refresh')) {
    getData.searchMaterielData()
}
//renderData.materialLists(data);
// 页面逻辑处理
// 新增按钮跳转新增页面
function addProduct () {
    // 存储添加跳转标识
    var params = {
        materielId: 'add',
    }
    sessionStorage.setItem('materielId', JSON.stringify(params))
    var singleUrl = layer.open({
        type: 2,
        title: '新增物料号',
        content:
            '../../../html/Customer/accountAystem/materialinfo_single.html',
    })
    layer.full(singleUrl)
}
//renderData.materialLists(data);
// 点击查询按钮获取数据
function searchBtn () {
    getData.searchMaterielData()
}
// 修改
function modify (productType, tag) {
    // 修改物料的入参
    var materielId = tag.getAttribute('data-type')
    // 商品类型 productType 商品类型
    var params = {
        materielId: materielId,
        productType: productType,
    }
    // 存储在本地中
    sessionStorage.setItem('materielId', JSON.stringify(params))
    // 跳转物料号修改页面
    var singleUrl = layer.open({
        type: 2,
        title: '修改物料号',
        content:
            '../../../html/Customer/accountAystem/materialinfo_single.html',
    })
    layer.full(singleUrl)
}
// 删除
function cancelData (materielId) {
    getData.deleteMaterielById(materielId)
}
// 批量删除
function multipleCancel () {
    //var rows = $('.check').find('input[type=checkbox][name=checkbox]:checked');
    var params = []
    $.each($('input:checkbox'), function (index, item) {
        if (this.checked) {
            var materielId = item.getAttribute('data-type')
            params.push(materielId)
        }
    })
    // 调取删除接口
    getData.deleteMaterielById(params)
    // params如果为空说明没有选择删除对象
    if (params.length <= 0) {
        $.Huimodalalert('请选择要删除的数据', 2000)
    }
}
// 导入按钮
function importExcel () {
    $('#fileUp').trigger('click')
    //$("#tipmessage").css({"display":"block"})
}
// 下载错误信息
// 下载错误值
function errorvalue () {
    $('#errorvalue').attr(
        'href',
        root.member.materialExport +
        '?operateUserId=' +
        operateUserId +
        '&moduleType=' +
        20
    )
}
function Imports () {
    var name = $('#fileUp').val()
    var result = /\.[^\.]+/.exec(name)
    if (result != '.xlsx' && result != '.xls') {
        $.Huimodalalert('格式不正确！', 2000)
        return false
    }
    var formData = new FormData()
    formData.append('file', $('#fileUp')[0].files[0])
    formData.append('operateUserId', operateUserId)
    formData.append('operateUserName', operateUserName)
    formData.append('mainCustomerId', mainCustomerId)
    $.ajax({
        url: root.member.importMaterielProductExcel,
        cache: false, //禁用缓存
        type: 'POST',
        // 告诉jQuery不要去处理发送的数据
        processData: false,
        // 告诉jQuery不要去设置Content-Type请求头
        contentType: false,
        data: formData,
        success: function (data) {
            $('#fileUp').val('')
            if (data.errorCode == 0) {
                //$.Huimodalalert('导入成功！', 2000)
                var success_num = data.data.success_num //导入的成功数
                var error_num = data.data.error_num //导入的失败数
                if (Number(error_num) > 0) {
                    $('#successnum').text(success_num)
                    $('#errornum').text(error_num)
                    $('#tipmessage').css({ display: 'block' })
                    setTimeout(function () {
                        $('#tipmessage').css({ display: 'none' })
                    }, 5000)
                }
                getData.searchMaterielData()
            } else if (data.errorCode == 1 || data.errorCode == 5) {
                $.Huimodalalert(data.msg, 1000)
            } else {
                $.Huimodalalert('导入失败', 2000)
            }
        },
    })
}

// 下载模板
function downLoadModel () {
    $('#down_load').attr(
        'href',
        root.publics.downLoadFromUrl +
        '?urlStr=https://fsyuncai-file.oss-cn-beijing.aliyuncs.com/common/20210724102544270214.xlsx&fileName=WLH'
    )
}
